package com.daluzy.chmanager.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.cazaea.sweetalert.SweetAlertDialog;
import com.daluzy.chmanager.MyApplication;
import com.daluzy.chmanager.R;
import com.daluzy.chmanager.bean.Account;
import com.daluzy.chmanager.bean.Area;
import com.daluzy.chmanager.bean.Employee;
import com.daluzy.chmanager.util.TelephoneUtil;
import com.xiasuhuei321.loadingdialog.view.LoadingDialog;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;

/**
 * 添加后勤人员
 */
public class AddEmployeeActivity extends AppCompatActivity {

    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.et_employee_name)
    EditText etEmployeeName;
    @BindView(R.id.et_employee_phone)
    EditText etEmployeePhone;
    @BindView(R.id.tv_employee_area)
    TextView tvEmployeeArea;
    @BindView(R.id.tv_add_commit)
    TextView tvAddCommit;
    @BindView(R.id.radio_btn_employee_male)
    RadioButton radioBtnEmployeeMale;
    @BindView(R.id.radio_btn_employee_female)
    RadioButton radioBtnEmployeeFemale;
    @BindView(R.id.radio_group_employee_sex)
    RadioGroup radioGroupEmployeeSex;
    private String employeeName;
    private String employeePhone;
    private Area area;
    private String sex = "男";
    private LoadingDialog loadingDialog;
    private int type = 0;
    private Employee employee;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_employee_daluzy);
        ButterKnife.bind(this);
        type = getIntent().getIntExtra("type", 0);
        if (type == 1) {
            tvAddCommit.setText("确认");
            tvTitle.setText("后勤人员信息修改");
            employee = (Employee) getIntent().getSerializableExtra("employee");
            etEmployeeName.setText(employee.getEmployee_name());
            etEmployeePhone.setText(employee.getEmployee_phone());
            if (employee.getEmployee_sex().equals("男")) {
                sex = "男";
                radioGroupEmployeeSex.check(R.id.radio_btn_employee_male);
            } else {
                sex = "女";
                radioGroupEmployeeSex.check(R.id.radio_btn_employee_female);
            }
        }else {
            radioGroupEmployeeSex.check(R.id.radio_btn_employee_male);
        }

        loadingDialog = new LoadingDialog(this);
        radioGroupEmployeeSex.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.radio_btn_employee_male) {
                    sex = "男";
                } else {
                    sex = "女";
                }
            }
        });
    }

    @OnClick({R.id.iv_back, R.id.tv_employee_area, R.id.tv_add_commit})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_employee_area:
                Intent intent = new Intent(AddEmployeeActivity.this, SelectAreaActivity.class);
                startActivityForResult(intent, 2021);
                break;
            case R.id.tv_add_commit:
                tvAddCommit.setEnabled(false);
                check();
                break;
        }
    }

    private void check() {
        employeeName = etEmployeeName.getText().toString().trim();
        employeePhone = etEmployeePhone.getText().toString().trim();
        if (TextUtils.isEmpty(employeeName)) {
            Toast.makeText(AddEmployeeActivity.this, "请输入后勤人员姓名", Toast.LENGTH_SHORT).show();
            tvAddCommit.setEnabled(true);
            return;
        }
        if (TextUtils.isEmpty(employeePhone)) {
            Toast.makeText(AddEmployeeActivity.this, "请输入后勤人员手机号码", Toast.LENGTH_SHORT).show();
            tvAddCommit.setEnabled(true);
            return;
        }
        if (!TelephoneUtil.checkCellphone(employeePhone)) {
            Toast.makeText(AddEmployeeActivity.this, "请输入正确的手机号码", Toast.LENGTH_SHORT).show();
            tvAddCommit.setEnabled(true);
            return;
        }
        if (type != 1) {
            if (area == null) {
                Toast.makeText(AddEmployeeActivity.this, "请选择区域", Toast.LENGTH_SHORT).show();
                tvAddCommit.setEnabled(true);
                return;
            }
        }
        if (type != 1)
            checkAccount();
        else updateEmployee();
    }

    private void updateEmployee() {
        employee.setAccount(employeePhone);
        employee.setEmployee_phone(employeePhone);
        employee.setEmployee_name(employeeName);
        if (area != null)
            employee.setEmployee_area(area.getArea_name());
        employee.setEmployee_sex(sex);
        employee.update(employee.getObjectId(), new UpdateListener() {

            @Override
            public void done(BmobException e) {
                if (e == null) {
                    MyApplication.getIntance().setEmployee(employee);
                    Toast.makeText(AddEmployeeActivity.this, "修改成功", Toast.LENGTH_SHORT).show();
                    finish();
                } else {
                    Toast.makeText(AddEmployeeActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }

        });
    }

    private void checkAccount() {
        if (loadingDialog != null)
            loadingDialog.show();
        BmobQuery<Account> query = new BmobQuery<>();
        query.addWhereEqualTo("account", employeePhone);
        query.order("-createdAt")
                .findObjects(new FindListener<Account>() {
                    @Override
                    public void done(List<Account> object, BmobException e) {
                        if (e == null) {
                            if (object != null && object.size() > 0) {
                                final SweetAlertDialog mDialog = new SweetAlertDialog(AddEmployeeActivity.this, SweetAlertDialog.NORMAL_TYPE)
                                        .setTitleText("提示")
                                        .setContentText("该账号已存在，是否直接绑定？")
                                        .setCustomImage(null)
                                        .setCancelText("否")
                                        .setConfirmText("是")
                                        .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                            @Override
                                            public void onClick(SweetAlertDialog sweetAlertDialog) {
                                                sweetAlertDialog.dismiss();
                                                if (loadingDialog != null)
                                                    loadingDialog.close();
                                            }
                                        }).setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                            @Override
                                            public void onClick(SweetAlertDialog sweetAlertDialog) {
                                                sweetAlertDialog.dismiss();
                                                addEmployee();
                                            }
                                        });
                                mDialog.show();
                            } else {
                                addAccount();
                            }

                        } else {
                            Toast.makeText(AddEmployeeActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                            if (loadingDialog != null)
                                loadingDialog.close();
                        }
                        tvAddCommit.setEnabled(true);
                    }
                });
    }

    private void addAccount() {
        Account account = new Account();
        account.setAccount(employeePhone);
        account.setPassword("123456");
        account.save(new SaveListener<String>() {
            @Override
            public void done(String s, BmobException e) {
                if (e == null) {
                    addEmployee();
                } else {
                    Toast.makeText(AddEmployeeActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                    if (loadingDialog != null)
                        loadingDialog.close();
                }

            }
        });
    }

    private void addEmployee() {
        employee = new Employee();
        employee.setAccount(employeePhone);
        employee.setEmployee_id(String.valueOf(System.currentTimeMillis()));
        employee.setEmployee_phone(employeePhone);
        employee.setEmployee_name(employeeName);
        employee.setEmployee_area(area.getArea_name());
        employee.setEmployee_sex(sex);
        employee.save(new SaveListener<String>() {
            @Override
            public void done(String objectId, BmobException e) {
                if (e == null) {
                    Toast.makeText(AddEmployeeActivity.this, "添加成功", Toast.LENGTH_SHORT).show();
                    finish();
                } else {
                    Toast.makeText(AddEmployeeActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                }
                if (loadingDialog != null)
                    loadingDialog.close();
            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 2021 && resultCode == 2021) {
            area = (Area) data.getSerializableExtra("area");
            if (area != null)
                tvEmployeeArea.setText(area.getArea_name());
        }
    }
}
